package com.zcxy.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxy.core.bean.PageQuery;
import com.zcxy.mybatis.service.BaseServiceImpl;
import com.zcxy.mybatis.util.RelationHelper;
import com.zcxy.sys.entity.SysAutocode;
import com.zcxy.sys.entity.SysAutocodeItem;
import com.zcxy.sys.mapper.SysAutocodeMapper;
import com.zcxy.sys.pojo.SysAutocodeVo;
import com.zcxy.sys.service.IGenHelperService;
import com.zcxy.sys.service.ISysAutocodeItemService;
import com.zcxy.sys.service.ISysAutocodeService;
import com.zcxy.util.BeanCopierUtil;
import com.zcxy.util.FileUtil;
import com.zcxy.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户Service业务层处理
 *
 * @author zcc
 * @email 860474958@qq.com
 * @date 2020-06-01
 */
@Service
@Slf4j
@Configuration
@PropertySource({"classpath:generator.properties"})
public class SysAutocodeServiceImpl extends BaseServiceImpl<SysAutocodeMapper, SysAutocode>
        implements ISysAutocodeService {


    @Autowired
    private Environment env;

    @Autowired
    private ISysAutocodeItemService iSysAutocodeItemService;
    @Autowired
    private IGenHelperService genHelperService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IPage<SysAutocodeVo> queryPageList(PageQuery<SysAutocode> queryVo) {
        QueryWrapper queryWrapper = queryVo.getT() != null ? new QueryWrapper(queryVo.getT()) : new QueryWrapper();
        Page page = new Page(queryVo.getPageNo(), queryVo.getPageSize());
        IPage<SysAutocode> pageResult = baseMapper.selectPage(page, queryWrapper);
        return BeanCopierUtil.copyPage(pageResult, SysAutocodeVo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysAutocodeVo> queryList() {
        SysAutocode SysAutocode = new SysAutocode();
        QueryWrapper queryWrapper = new QueryWrapper(SysAutocode);
        List<SysAutocode> SysAutocodes = baseMapper.selectList(queryWrapper);
        return BeanCopierUtil.copyListToList(SysAutocodes, SysAutocodeVo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAutocode addSysAutocode(SysAutocode sysAutocode) {
        //1.TODO 校验相关数据
        if(StringUtils.isEmpty(sysAutocode.getId())){
            sysAutocode.setClassNameS(StringUtils.toCamelCase(sysAutocode.getTableName()));
            baseMapper.insert(sysAutocode);
            List<SysAutocodeItem> sysAutocodeItemsFromTable=baseMapper.queryMysqlColums(sysAutocode.getTableName());
            initSysAutocodeItems(sysAutocodeItemsFromTable,sysAutocode.getId());
            iSysAutocodeItemService.saveBatch(sysAutocodeItemsFromTable);
            sysAutocode.setSysAutocodeItems(sysAutocodeItemsFromTable);
        }
        else{

            SysAutocode sysAutocodeDb=baseMapper.selectById(sysAutocode.getId());
            BeanCopierUtil.copyObject(sysAutocodeDb,sysAutocode);
            baseMapper.updateById(sysAutocode );
            initSysAutocodeItems(sysAutocode.getSysAutocodeItems(),sysAutocode.getId());
            if(CollectionUtil.isNotEmpty(sysAutocode.getSysAutocodeItems())){
                sysAutocode.getSysAutocodeItems().forEach(sysAutocodeItem -> {
                    iSysAutocodeItemService.saveOrUpdate(sysAutocodeItem);
                });
            }

        }
       return  sysAutocode;
    }
     public void    initSysAutocodeItems( List<SysAutocodeItem> sysAutocodeItems,String id){
        if(CollectionUtil.isNotEmpty(sysAutocodeItems)){
            int k=1;
            for(int j=0;j<sysAutocodeItems.size();j++){
                SysAutocodeItem i = sysAutocodeItems.get(j);
                i.setJavaType(env.getProperty(i.getType(), "String"));
                i.setColumnNameB(StringUtils.toCapitalizeCamelCase(i.getColumnName()));
                i.setJavaName(StringUtils.toCamelCase(i.getColumnName()));
                i.setParentId(id);
                i.setSort(k);
                k++;
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSysAutocode(SysAutocodeVo queryVo) {
        SysAutocode SysAutocodedb = baseMapper.selectById(queryVo.getId());
        BeanCopierUtil.copyObject(queryVo, SysAutocodedb);
        baseMapper.updateById(SysAutocodedb);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeAllSysAutocode(List<String> ids) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("id", ids);
        baseMapper.delete(queryWrapper);


    }

    @Override
    public void download(SysAutocode SysAutocode, HttpServletResponse response) throws IOException {
        List<SysAutocode> SysAutocodes = baseMapper.selectList(new QueryWrapper<>(SysAutocode));
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysAutocode SysAutocodeExcel : SysAutocodes) {
            Map<String, Object> map = new LinkedHashMap<>();

            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void genCode(String codeId, HttpServletResponse response) {
        SysAutocode sysAutocode=baseMapper.selectById(codeId);
        QueryWrapper queryWrapper=new QueryWrapper(new SysAutocodeItem());
        queryWrapper.orderByAsc("sort");
        SysAutocodeVo  sysAutocodeVo= RelationHelper.render(BeanCopierUtil.copyObject(sysAutocode, SysAutocodeVo.class),queryWrapper);
        genHelperService.genCode(sysAutocodeVo, response);
    }

    @Override
    public List<SysAutocode> getAllTables(String tableName) {
        ///@TODO 后期加上不同数据库兼容
       return   baseMapper.queryMysqlTables(tableName);
    }

    @Override
    public SysAutocodeVo viewSysAutocode(String id) {
        SysAutocode sysAutocode=baseMapper.selectById(id);
        QueryWrapper queryWrapper=new QueryWrapper(new SysAutocodeItem());
        queryWrapper.orderByAsc("sort");
        SysAutocodeVo  sysAutocodeVo= RelationHelper.render(BeanCopierUtil.copyObject(sysAutocode, SysAutocodeVo.class),queryWrapper);
        return sysAutocodeVo;
    }


}
